import {observable, action, toJS} from 'mobx';
import {WeaForm, WeaTableNew} from 'comsMobx';
import * as API from '../apis/weeso';
import {Modal, message} from 'antd';
import isEmpty from 'lodash/isEmpty';
import {WeaLocaleProvider} from 'ecCom';
import weesoSeachSetStore from './weesoSeachSetStore';
const {TableStore} = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;

class WeesoStore {
  //getBaseData获取是否成功
  @observable spinning = false;
  //数据加载
  @observable loading = false;
  //getBaseData返回数据
  @observable baseDadas = {};
  @observable contentType = [];
  @observable searchType = [];
  
  //保存微搜个人搜索设置
  @observable numberValue = '';
  @observable searchValue = '';
  @observable sortValue = '';
  
  //顶部热点、设置相关
  @observable sysadminVisible = false;
  @observable sysVisible = false;
  @observable setVisible = false;
  @observable perVisible = false;
  
  //input输入框相关
  @observable iconClick = false;
  
  //tab默认显示
  @observable defaultKey = 'CONTENT'; //查询类型   内容：CONTENT、图片:PICTURE
  @observable defalutMoreKey = 'ALL'; //查询模块    WF、DOC、WKP等
  
  //微搜查询数据
  @observable inputValue = ''; //搜索内容
  @observable previousInputValue = '';
  // @observable otherString = {}; //查询工具内容
  @observable sourceType = 'PC';
  @observable page = '1'; //当前页
  @observable pages = '1'; //总共页数
  
  //doSearch返回数据
  @observable searchDatas = {};
  @observable searchResult = [];
  @observable emptyResult = '';
  @observable imageResult = [];
  
  //创建时间、日期等选择
  @observable startDate = '';
  @observable endDate = '';
  
  //浏览按钮相关
  @observable browsertype = '';
  
  //判断是否调用doSearch
  @observable isSearch = false;
  //管理员权限
  @observable showAdmin = false;
  
  // 获取常用词关联
  @observable hotkeys = [];
  @observable showHotKeys = false;
  
  //input上一排tab计算
  @observable widthMap = {};
  @observable copiedcontentType1 = []; //深拷贝后的contentType ，
  @observable copiedcontentType2 = []; //dropdowm 剩余参数
  
  //热词上下键切换效果
  @observable myKey = -1;
  @observable currentInputValue = '';
  
  @observable isSearchSucess = false;
  
  
  //工具展示改造
  @observable showToolPopover = false;
  @observable maskClosable = true;
  
  // 高级搜索数据
  @observable searchInfo = {};
  @observable searchForm = new WeaForm();
  @observable searchConditions = [];
  @observable isShowSearchIcon = false; //是否显示高级搜索图标--选择搜搜条件，并搜索之后
  @observable getTypeDatas = []; //保存高级搜索取到的值
  @observable searchKey = '';
  
  
  //记录用户使用习惯
  @observable userDatas = [];
  @observable userData1 = { 
    type: 'pageTrack',
    userAgent: navigator.userAgent,
    timeStamp: '',
    timeStayTime: '',
  }
  @observable timeStamp1 = '';
  @observable timeStamp2 = '';
  
  //路由跳转记录
  @observable isRouting  = false;
  @observable inputNode = null;
  @observable selectionStart = 0;
  @observable selectionEnd = 0;
  
  //
  @observable isHotkeySearch = false; //记录是否热词搜索
  @observable isCustomer = false; //记录是否外部切入微搜

  @observable workPlanVisible = false; //日程引入

  @observable showSubmitIcon = false; //是否显示微搜结果提交按钮

  @observable isLocked = false; //是否锁定搜索

  @observable wpLoaded = false;

  @observable smLoaded = false;

  @observable supportSkipSearch = false;

  @observable skipSearchParams = {
    currentPage: 0,
    lastRealNumber: 0,
  };
  //支持无侵入开发的参数-勿删
  @observable searchPageParams = {};

  @observable ecodeTitleParams = {
  };
  //支持无侵入开发的参数-勿删

  @observable tagsDatas = {
    commonConditions: [
      {name: '1111', key: 1},
      {name: '2222', key: 2, canDel: true},
    ],
    conditionSpining: false,
    conditionSetTableStore: new TableStore(),
    logoVisible: true,
  };


  @observable cuspage_status = undefined;
  @observable historySearchList = undefined;
  @observable page_icon = undefined;
  @observable page_resultLogo = undefined;
  @observable page_resultShowLogo = undefined;
  @observable page_showCommonConditions = undefined;
  @observable page_showHistory = undefined;
  @observable page_showIcon = undefined;
  @observable page_title = undefined; 
  @observable tagList = [];
  @observable urlParams = {};
  @observable isSetServer = true;
  @observable isSetServerMsg = '';

  @action

  //初始化微搜初始化页面
  initWeeso = (page_uuid) => {
    this.getBaseData(undefined, undefined, undefined, page_uuid);
    this.isSearch = false;
    this.inputValue = '';
    this.showHotKeys = false;
    this.iconClick = false;
    this.defaultKey = 'CONTENT';
    this.defalutMoreKey = 'ALL';
    this.showHotKeys = false;
    this.commonInit();
  };
  
  //初始化微搜查询页面
  initWeesoResult = () => {
    this.isSearch = true;
    this.commonInit();
  };

  setWPLoaded = (bool) => this.wpLoaded = bool;

  setSMLoaded = (bool) => this.smLoaded = bool;
  
  
  //其他公共初始化
  commonInit = () => {
    this.showTool = false;
    this.otherString = {};
    this.pages = '1';
    this.page = '1';
    this.myKey = -1;
    this.searchDatas = {};
    this.imageResult = [];
    this.emptyResult = '';
    this.searchResult = [];
    this.toolChangeInit();
  }
  
  //工具切换初始化
  toolChangeInit = () => {
    this.pages = '1';
    this.page = '1';
    this.myKey = -1;
    this.searchDatas = {};
    this.imageResult = [];
    this.emptyResult = '';
    this.searchResult = [];
  }
  
  setState = (params = {}, callback) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
    typeof callback == 'function' && callback();
    return this;
  }

  setUrlParams = (params, callback) => {
    this.urlParams = params;
    typeof callback == 'function' && callback();
  }
  
  //获取初始数据
  getBaseData = (showError = true, callRouting, callSearch, page_uuid) => {
    this.spinning = true;
    let params = {
      page_uuid: page_uuid
    };
    API.getBaseData(params).then(data => {
      this.spinning = false;
      if (data.FLAG == -1) {
        this.isSetServer = false;
        this.isSetServerMsg = data.MSG;
        if(callRouting)callRouting();
        if(showError){
          Modal.error({
            title: getLabel(15172, "系统提示"),
            content: <span className="content-img" dangerouslySetInnerHTML={{__html: data.MSG}}/>,
          });
        }
      }else {
        this.isSetServer = true;
        this.isSetServerMsg = '';

        if(callSearch)callSearch();
      }
      this.baseDadas = data;
      this.contentType = data.contentType && data.contentType;
      this.searchType = data.searchType && data.searchType;
      this.searchInfo = data.searchInfo && data.searchInfo;

      this.supportSkipSearch = data && data.supportSkipSearch ? data.supportSkipSearch : false;

      this.changeKey(this.defalutMoreKey);

      //topTabs初始
      if(Object.keys(this.widthMap).length == 0){
        this.copiedcontentType1 = this.contentType;
      }
  
      data.searchSet && data.searchSet.numperpage && data.searchSet.numperpage.length!==0 &&
      data.searchSet.numperpage.map((item, index) => {
        if (item.selected == true) {
          this.numberValue = data.searchSet.numperpage[index].key
        }
      });
  
      data.searchSet && data.searchSet.sortField && data.searchSet.sortField.length!==0 &&
      data.searchSet.sortField.map((item, index) => {
        if (item.selected == true) {
          this.sortValue = data.searchSet.sortField[index].key
        }
      });
  
      data.searchSet && data.searchSet.searchField && data.searchSet.searchField.length!==0 &&
      data.searchSet.searchField.map((item, index) => {
        if (item.selected == true) {
          this.searchValue = data.searchSet.searchField[index].key
        }
      });

      if(data.api_status) {
        this.cuspage_status = data.cuspage_status;
        this.historySearchList = data.historySearchList;
        this.page_icon = data.page_icon;
        this.page_resultLogo = data.page_resultLogo;
        this.page_resultShowLogo = data.page_resultShowLogo;
        this.page_showCommonConditions = data.page_showCommonConditions;
        this.page_showHistory = data.page_showHistory;
        this.page_showIcon = data.page_showIcon;
        this.page_title = data.page_title;
        this.tagList = data.tagList;
        let urlP = {};
        if(this.urlParams.type) {
          urlP = {
            ...urlP,
            search_type: this.urlParams.type
          };
        }
        if(this.urlParams.hideTitle === 'true' || this.urlParams.hideTitle === '1') {
          urlP = {
            ...urlP,
            topTabsVisible: false
          };
        }
        if(weesoSeachSetStore) {
          weesoSeachSetStore.setState({
            search_type: data.search_type,
            page_descStr: data.page_descStr,
            page_uuid: data.page_uuid,
            topTabsVisible: data.search_type === 'ALL',
            ...urlP
          });
        }
      }
    })
  }
  
  //tabs重排
  resortTopTaps = () => {
    let
      top = [], right = [], contentType = toJS(this.contentType), allWidth = 489;
    //如果没有或者widthMap,不进行计算
    if (!this.widthMap) return;
    
    let currentWidth;
    for (let key in this.widthMap) {
      if (key == this.defalutMoreKey) {
        currentWidth = this.widthMap[key];
      }
    }
    let restWidth = allWidth - currentWidth - 10;
    let sumWidth = 0, isTop = true;
    contentType && contentType.length > 0 && contentType.forEach((item) => {
      if (item.key == this.defalutMoreKey) {
        if (isTop) {
          restWidth += currentWidth;
          sumWidth += currentWidth;
        }
        top.push(item)
      } else {
        sumWidth += this.widthMap[item.key];
        if (isTop && sumWidth < restWidth) {
          top.push(item);
        } else {
          //isTop -- 保证不会出现上一个元素长了放不下，把下一个元素放到top里面
          isTop = false;
          right.push(item)
        }
      }
      this.copiedcontentType1 = top;
      this.copiedcontentType2 = right;
    })
  }
  
  
  //获取常用词关联
  getAssociate = (params = {key: ''}) => {
    API.getAssociate(params).then(result => {
      this.hotkeys = result.result
    })
  }
  
  
  //切换tab回调 -- 工具表单的处理（路由跳转也需要此处理）
  changeKey = (key, isFirst = false) => {
    this.searchForm = new WeaForm();
    const source = toJS(this.searchInfo);
    if (isEmpty(source) && isFirst) {
      let interval = setInterval(() => {
        if (!isEmpty(source)) {
          this.searchConditions = source[key];
          this.searchForm.initFormFieldObj(toJS(this.searchConditions));
          clearInterval(interval);
        }
      }, 10)
    } else {
      if (!isEmpty(source)) {
        this.searchConditions = source[key];
        this.searchForm.initFormFieldObj(toJS(this.searchConditions));
      }
    }
  }
  
  resetForm = () => {
    this.searchForm.reset();
  }
  
  //处理搜索工具表单数据
  dealSearchParams = () => {
    let searchDatas = {};
    if (Object.keys(this.baseDadas).length == 0) {
      return searchDatas = '';
    } else {
      let datas = toJS(this.searchConditions);
      const searchParams = this.searchForm.getFormParams();
      let
        resultDay = toJS(this.baseDadas.timeSag.day) || [],
        resultWeek = toJS(this.baseDadas.timeSag.week) || [],
        resultMonth = toJS(this.baseDadas.timeSag.month) || [],
        resultYear = toJS(this.baseDadas.timeSag.year) || [];
      datas && datas.length>0 && datas.map(item => {
        for (let key in searchParams) {
          if (searchParams[key].toString() != '' && key == item.domkey[0]) {
            const type = item.conditionType.toUpperCase();
            if (type == 'BROWSER') {
              if (item.domkey[0] == 'seccategory') {
                searchDatas['firstDirectory'] = searchParams[key].split(',');
              } else {
                searchDatas[item.domkey] = searchParams[key].split(',');
              }
            } else if (type == 'RANGEPICKER') {
              if (searchParams.CREATEDATE_date_select == '5') {
                searchDatas.CREATEDATE = searchParams[key];
              }
              if(searchParams.BEGINDATE_date_select == '5'){
                searchDatas.BEGINDATE = searchParams[key];
              }
            } else if (type == 'SELECT') {
              if (key == 'CREATEDATE_date_select') {
                if (searchParams[key] == '1') {
                  searchDatas.CREATEDATE = resultDay;
                } else if (searchParams[key] == '2') {
                  searchDatas.CREATEDATE = resultWeek;
                } else if (searchParams[key] == '3') {
                  searchDatas.CREATEDATE = resultMonth;
                } else if (searchParams[key] == '4') {
                  searchDatas.CREATEDATE = resultYear;
                }
              } else if (key == 'BEGINDATE_date_select') {
                if (searchParams[key] == '1') {
                  searchDatas.BEGINDATE = resultDay;
                } else if (searchParams[key] == '2') {
                  searchDatas.BEGINDATE = resultWeek;
                } else if (searchParams[key] == '3') {
                  searchDatas.BEGINDATE = resultMonth;
                } else if (searchParams[key] == '4') {
                  searchDatas.BEGINDATE = resultYear;
                }
              } else {
                searchDatas[key] = searchParams[key];
              }
            } else if (type == 'INPUT') {
              searchDatas[key] = searchParams[key];
            }
          }
        }
      })
      if(JSON.stringify(searchDatas) == '{}'){
        return searchDatas = ''
      }else {
        return JSON.stringify(searchDatas);
      }
    }
  }

  preSearch = (params) => {
    if(this.showToolPopover){this.showToolPopover = false;}
    this.showHotKeys = false;
  
    this.inputValue && this.inputValue !=='' && this.doSearch(undefined, params);
  }
  
  //微搜查询
  doSearch = (params = {
    key: this.inputValue,
    contentType: this.defalutMoreKey,
    // otherString: this.isCustomer ? '' : this.dealSearchParams(),
    otherString: this.urlParams.otherString,
    sourceType: this.sourceType,
    searchType: this.defaultKey,
    page: this.page
  }, otherString) => {
    if(this.isSetServer === false) return; // 未配置微搜
    this.isLocked = true;
    // this.showHotKeys = false;

    // if(this.loading) return;
    this.setState({
      loading: true,
      emptyResult: '',
      showHotKeys: false,
      searchResult: []
    })
    params = {
      ...params,
      ...otherString,
      page_uuid: weesoSeachSetStore.page_uuid,
      searchTagId: weesoSeachSetStore.searchTagParams.key || '',
      ...this.skipSearchParams
    }
    this.skipSearchParams.currentPage = params.page;
    if(weesoSeachSetStore) {
      weesoSeachSetStore.doSaveHistorySearch({
        searchkey: params.key
      });
    }
    API.doSearch(params).then(result => {
      this.isLocked = false;
      this.loading = false;
      //this.hotkeys = [];

      const normal = result.normalkey;
      if ("-1" == result.FLAG || (normal == this.inputValue)) {
        this.isSearchSucess = true;
        this.searchDatas = result;
        this.pages = result.pages;

        this.skipSearchParams.lastRealNumber = result.lastRealNumber || -1;

        // 这部分是对快速搜索时，判断上次请求是否完成，取最新的搜索结果-start
        if (result.FLAG == -1) {
          Modal.error({
            title: getLabel(15172, "系统提示"),
            content: <span className="content-img" dangerouslySetInnerHTML={{__html: result.MSG}}/>,
          });
        } else if (result.FLAG == -99 ) {
          this.emptyResult = result.MSG
        } else {
          this.searchResult = result.result;
        }
        // 这部分是对快速搜索时，判断上次请求是否完成，取最新的搜索结果-end

        if (result.FLAG != -1 && this.defaultKey == 'PICTURE') {
          this.imageResult = this.imageResult.concat(result.result)
        }
        if(result.contentType) {
          this.defalutMoreKey = result.contentType;
          this.resortTopTaps();
        }
      }

      //记录用户使用习惯
      if (this.timeStamp1 == '') {//表示第一次进入
        this.timeStamp2 = new Date().getTime();
        this.timeStamp1 = this.timeStamp2;
      } else {//此后进入，计算时间差，调接口记录数据
        this.timeStamp1 = this.timeStamp2;
        this.timeStamp2 = new Date().getTime();
        this.userData1 = {
          ...this.userData1,
          timeStamp: String(this.timeStamp1),
          timeStayTime: String(this.timeStamp2 - this.timeStamp1)
        }
        this.userDatas.push(this.userData1);
        
        this.collectUserData({userDatas: JSON.stringify(this.userDatas)});
      }
    })
  }

  //保存微搜个人搜索设置
  saveSearchSet = (params = {
    numperpage: this.numberValue,
    searchField: this.searchValue,
    sortField: this.sortValue
  }) => {
    API.saveSearchSet(params).then(result => {
      if (result.flag == true) {
        this.doSearch()
      } else {
        Modal.error({
          title: getLabel(15172, "系统提示"),
          content: getLabel(22620, "保存失败"),
        });
      }
    })
  }
  
  //记录用户使用习惯
  collectUserData = (userDatas) => {
    API.collectUserData(userDatas).then(() => {
        this.userDatas = []
      }
    )
  }

  //是否显示微搜结果提交按钮
  showSubmit = () => {
    API.showSubmit().then(result => {
        this.showSubmitIcon = result.ret;
      }
    )
  }

  doSubmit = () => {
    const params = {
      key: this.inputValue,//搜索关键字
      page: this.page, //当前页数
      pageSize: this.numberValue, //每页显示条数
      searchType: this.searchValue, //搜索类型（CONTENT，TITLE）
      sort: this.sortValue, //排序方式
      contentType: this.defalutMoreKey, //搜索tab
      sourceType: this.sourceType, //来源（PC，mobile）
      searchField: this.defaultKey, //搜索范围（内容，图片）
      condition: this.isCustomer ? '' : this.dealSearchParams(), //高级搜索条件{json串}
    }
    Modal.confirm({
      title: getLabel(15172,'系统提示'),
      content: getLabel(384971,'不是我想要的搜索结果，确认提交？'),
      okText: getLabel(826,'确定'),
      cancelText: getLabel(31129,'取消'),
      onOk: () => {this.submitResult({...params})}
    });
  }

  //微搜结果提交
  submitResult = (params) => {
    API.submitResult(params).then(result => {
        if(result.ret){
          message.success(getLabel(83923,'提交成功！'));
        }else {
          message.error(getLabel(384535,'提交失败！'));
        }
      }
    )
  }

  // 常用条件设置
  getConditionSetTable = (params, callback) => {
    API.getConditionSetTable(params).then(result => {
      if(result.ret == 'noright'){
      }else {
        this.tagsDatas.conditionSetTableStore.getDatas(result.sessionkey, 1);
        typeof callback === 'function' && callback();
      }
    })
  }

}

const weesoStore = new WeesoStore();
export default weesoStore;
